<?php

/**
 * Response class.
 *
 * @author Eugene Zabolotniy
 */
class Service_Response
{
    protected $_code = 200;
    protected $_label = 'OK';
    protected $_content = array();

    public function setContent($section, $content)
    {
        $this->_content[$section] = $content;
        return $this;
    }

    public function getContent($section)
    {
        if (isset($this->_content[$section])) {
            return $this->_content[$section];
        } 
        return false;
    }

    public function getCode()
    {
        return $this->_code;
    }
    
    public function send()
    {
        $content = $this->_contentString();

        header("HTTP/1.1 {$this->_code} {$this->_label}");
        header('Content-Type: text/xml; charset=utf-8');
        header('Content-Length: ' . strlen($content));

        echo $content;
       
    }

    protected function _contentString()
    {
        if (!($this->_content instanceof Service_Resource_PresentationInterface)) {
            require_once 'Service/Presentation/Xml/Document.php';
            $this->_content = new Service_Presentation_Xml_Document('response', array(), $this->_content);
        }
        
        return $this->_content->serialize();
    }

    protected function _contentToXml($content)
    {
        $str = '';
        foreach ($content as $key => $part) {
            
            if (is_array($part) || $part instanceof Iterator) {
                $part = $this->_contentToXml($part);
            } elseif (!empty($part) && !is_numeric($part)) {
                $part = '<![CDATA['
                      . str_replace(']]>', ']]]]><![CDATA[>', $part) . ']]>';
            }

            if (is_numeric($key)) {
                $key = 'item';
            }
            
            $str .= "<{$key}>{$part}</{$key}>";
        }
        return $str;
    }
}
